package com.wxblockchain.wxbasemodule.base;

import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.wxblockchain.wxbasemodule.PermissionListener;
import com.wxblockchain.wxbasemodule.manager.ActivityManager;
import com.wxblockchain.wxbasemodule.utils.LogUtil;
import com.wxblockchain.wxbasemodule.utils.PermissionUtil;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

public abstract class BaseActivity extends Activity {

    private final String TAG = BaseActivity.class.getSimpleName();

    /**
     * 判断当前Activity是否在前台。
     */
    protected Boolean isActive = false;

    /**
     * 当前Activity的实例。
     */
    protected BaseActivity activity = null;

    private WeakReference<BaseActivity> weakRefActivity = null;

    private PermissionListener mListener = null;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        activity = this;
        weakRefActivity = new WeakReference<>(this);
        ActivityManager.getInstance().add(weakRefActivity);
    }


    @Override
    protected void onResume() {
        super.onResume();

        isActive = true;
    }

    @Override
    protected void onPause() {
        super.onPause();

        isActive = false;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        activity = null;
        ActivityManager.getInstance().remove(weakRefActivity);
    }

    /**
     * 将状态栏设置成透明。只适配Android 5.0以上系统的手机。
     */
    protected void transparentStatusBar() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            View decorView = getWindow().getDecorView();
            decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            getWindow().setStatusBarColor(Color.TRANSPARENT);
        }
    }

    /**
     * 检查和处理运行时权限，并将用户授权的结果通过PermissionListener进行回调。
     *
     * @param permissions
     * 要检查和处理的运行时权限数组
     * @param listener
     * 用于接收授权结果的监听器
     */
    protected void handlePermissions(String[] permissions, PermissionListener listener) {
        if (permissions == null || activity == null || listener == null) {
            return;
        }

        this.mListener = listener;

        PermissionUtil.reqPermissions(weakRefActivity,permissions,listener);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        if (requestCode == 1) {
            if (grantResults != null && grantResults.length > 0) {
                List<String> deniedPermissions = new ArrayList<>();
               for (int i=0,j=grantResults.length; i< j; i++) {
                   if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                       deniedPermissions.add(permissions[i]);
                   }
               }

                if (deniedPermissions.isEmpty()) {
                    mListener.onGranted();
                } else {
                    mListener.onDenied(deniedPermissions);
                }
            }
        }
    }

    /**
     * 隐藏软键盘。
     */
    protected void hideSoftKeyboard() {
        try {
            View view = getCurrentFocus();
            if (view != null) {
                IBinder binder = view.getWindowToken();
                InputMethodManager manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                manager.hideSoftInputFromWindow(binder, InputMethodManager.HIDE_NOT_ALWAYS);
            }
        } catch (Exception e) {
            LogUtil.e(TAG, e.getMessage());
        }
    }

    /**
     * 显示软键盘。
     */
    protected void showSoftKeyboard(EditText editText) {
        try {
            if (editText != null) {
                editText.requestFocus();
                InputMethodManager manager = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);

                manager.showSoftInput(editText, 0);
            }
        } catch (Exception e) {
            LogUtil.e(TAG, e.getMessage());
        }
    }

    protected void permissionsGranted() {
        // 由子类来进行具体实现
    }
}
